<?php

namespace app\api\controller\shop;

use addons\unidrink\model\Config;
use addons\unidrink\model\Product;
use app\admin\model\Onlineshopprofit;
use app\admin\model\Shoproom;
use app\admin\model\unidrink\Category;
use app\api\service\VbillService;
use app\common\controller\Api;

class Online extends Api
{
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();

    }

    public function addCate()
    {
        $shop_id = $this->request->param('shop_id');
        $name = $this->request->param('name');
        $id = $this->request->param('id');

        $unShopModel = new \app\admin\model\unidrink\Shop();
        $unShop = $unShopModel->where('shop_id',$shop_id)->find();
        if(!$unShop) $this->error("此店铺暂未开通酒水点餐,请联系技术开通");
        $unCateModel = new Category();
        if($id){
            $unCateModel->where('id',$id)->update(['name'=>$name,'status'=>'normal']);
        }else{
            $unCateModel->insert(['shop_id'=>$unShop['id'],'name'=>$name,'status'=>'normal']);

        }

        $this->success('成功');
    }

    public function deleteCate()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shop_id = $this->request->param('shop_id');
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
       // if($shop['user_id'] != $user['id']) $this->error("暂无权限操作".$user['id']);
        $unCateModel = new Category();
        $unCateModel->where('id',$id)->delete();

        $this->success('成功');
    }

    public function cateList()
    {
        $shop_id = $this->request->param('shop_id');
        $unShopModel = new \app\admin\model\unidrink\Shop();
        $unShop = $unShopModel->where('shop_id',$shop_id)->find();
        $unCateModel = new Category();
        $list = $unCateModel->where('shop_id',$unShop['id'])->select();

        $this->success('',$list);
    }

    public function goodList()
    {
        $cate_id = $this->request->param('cate_id');
        $shop_id = $this->request->param('shop_id');
        $keyword = $this->request->param('keyword');
        $unShopModel = new \app\admin\model\unidrink\Shop();
        $unShop = $unShopModel->where('shop_id',$shop_id)->find();
        $productModel = new Product();

        $where = array();
        if($cate_id != ""){
            $where['Product.category_id'] = $cate_id;
        }
        if($keyword != ""){
            $where['title'] = array('like','%'.$keyword.'%');

        }
        $where['Product.shop_id'] = $unShop['id'];
        $list = $productModel->with(['cate'])->where($where)->select();

        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }

        $this->success('',$list);
    }


    public function addGood()
    {
        $shop_id = $this->request->param('shop_id');
        $name = $this->request->param('name');
        $image = $this->request->param('url');
        $cateId =$this->request->param('cate_id');
        $specList = $this->request->param('specList');
        $id = $this->request->param('id');
        $specList = json_decode(htmlspecialchars_decode($specList), true);

        $isCheck = 1;
        $market_price = 0;
        $sales_price = 0;
        $specs = array();
        $obj = array();
        $obj['name'] = "规格";
        $child = array();

        $specContentList = array();
        foreach ($specList as $key=>$val){


            if($val['name'] == "" || $val['price'] == ""){
                $isCheck = -1;
            }
            $market_price = $val['price'];
            $sales_price = $val['price'];

            $child[] = $val['name'];
            $contentObj = array();
            $contentObj['code'] = 3;
            $contentObj['image'] = "";
            $contentObj['sales'] = 0;
            $contentObj['market_price'] = $market_price;
            $contentObj['sales_price'] = $sales_price;
            $contentObj['stock'] = 1000;
            $vs = array();
            $vs[] = $val['name'];
            $contentObj['value'] = $vs;
            $specContentList[] = $contentObj;

        }
        $obj['child'] = $child;
        $specs[] = $obj;
        if($isCheck == -1) $this->error("规格参数不正确");



        $productModel = new \app\admin\model\unidrink\Product();
        $unShopModel = new \app\admin\model\unidrink\Shop();
        $unShop = $unShopModel->where('shop_id',$shop_id)->find();
        $db = array();
        $db['shop_id'] = $unShop['id'];
        $db['updatetime'] = time();
        $db['switch'] = 1;
        $db['createtime'] = time();
        $db['category_id'] = $cateId;
        $db['title'] = $name;
        $db['image'] = $image;
        $db['images'] = $image;
        $db['market_price'] = $market_price;
        $db['sales_price'] = $sales_price;
        $db['specList'] = json_encode($specs);
        $db['specTableList'] = json_encode($specContentList);

        if($id != ""){
            $productModel->where('id',$id)->update($db);
        }else{
            $productModel->insert($db);

        }

        $this->success('成功');
    }

    public function deleteGood()
    {

        $id = $this->request->param('id');
        $productModel = new \app\admin\model\unidrink\Product();
        $productModel->where('id',$id)->delete();
        $this->success('成功');
    }

    public function goodDetail()
    {
        $id = $this->request->param('id');
        $productModel = new \app\admin\model\unidrink\Product();
        $product = $productModel->where('id',$id)->find();
        $product['image2'] = cdnurl($product['image'],true);
        $unCateModel = new Category();
        $cate = $unCateModel->where('id',$product['category_id'])->find();
        $product['cate_name'] = $cate['name'];


        $tableList = json_decode($product['specTableList'],true);
        $specList = array();
        foreach ($tableList as $key=>$val){

            $obj = array();
            $obj['id'] = "";
            $obj['name'] = $val['value'][0];
            $obj['price'] = $val['sales_price'];
            $specList[] = $obj;
        }

        $product['specList'] =  $specList;

        $this->success('',$product);
    }


    public function orderList()
    {

        $shop_id = $this->request->param('shop_id');
        $page = $this->request->param('page', 1);
        $pagesize = $this->request->param('pagesize', 10);
        $orderNo = $this->request->param('orderNo');
        $startTime = $this->request->param('startTime');
        $roomId = $this->request->param('roomId');


        $orderModel = new \addons\unidrink\model\Order();
        $unShopModel = new \app\admin\model\unidrink\Shop();
        $unShop = $unShopModel->where('shop_id',$shop_id)->find();
        $result = $orderModel->getOrdersByType2($unShop['id'], $page, $pagesize,$orderNo,$startTime,$roomId);
        $this->success('', $result);
    }

    public function getOrderDetail()
    {

        $order_no = $this->request->param('order_no');

        $orderModel = new \addons\unidrink\model\Order();
        $order = $orderModel
            ->with([
                'products' => function ($query) {
                    $query->field('id,order_id,image,number,price,spec,title,product_id');
                },
                'extend' => function ($query) {
                    $query->field('id,order_id,address_id,address_json');
                },
                'evaluate' => function ($query) {
                    $query->field('id,order_id,product_id');
                },
                'shop' => function ($query) {
                    $query->field('id,name,mobile,lng,lat,address_map,address');
                }
            ])
            ->where(['out_trade_no' => $order_no])->find();

        if ($order) {
            $order = $order->append(['paidtime', 'receivedtime', 'commentedtime', 'pay_type_text', 'type_text','user_id'])->toArray();

            // 送货地址
            if ($order['type'] == \addons\unidrink\model\Order::BUY_TYPE_TAKEOUT) {
                $address = json_decode($order['extend']['address_json'], true);
                $order['address'] = $address;
            } else {
                $order['address'] = [];
            }

            $userModel = new \app\admin\model\User();
            $user = $userModel->where('id',$order['user_id'])->find();

            $roomModel = new Shoproom();
            $room = $roomModel->where('id',$order['room_id'])->find();
            $order['room'] = $room;
            $order['username'] = $user['username'];
            $order['mobile'] = $user['mobile'];


            // 是否已评论
            $evaluate = array_column($order['evaluate'], 'product_id');
            foreach ($order['products'] as &$product) {
                $product['image'] = Config::getImagesFullUrl($product['image']);
                if (in_array($product['id'], $evaluate)) {
                    $product['evaluate'] = true;
                } else {
                    $product['evaluate'] = false;
                }
            }

            // 订单状态
            $order['order_status_text'] = $orderModel->orderStatusText($order);

            unset($order['evaluate']);
            unset($order['extend']);
        }

        $this->success('', $order);
    }

    public function done()
    {
        $order_no = $this->request->param('order_no');
        $orderModel = new \addons\unidrink\model\Order();
        $orderModel->where('out_trade_no',$order_no)->update(['have_received'=>1]);

        $this->success('成功');
    }

    public function refund ()
    {
        $order_no = $this->request->param('order_no');

        $orderModel = new \addons\unidrink\model\Order();
        $order = $orderModel->where('out_trade_no',$order_no)->find();

        $req = array();
        $req['mno'] = "399250109386123";
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $order_no;
        $req['amt'] = $order['order_price'];

        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);

        $result = json_decode($ret, true);
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }

        $onlineProfitModel = new Onlineshopprofit();
        $onlineProfitModel->where('order_id',$order['id'])->delete();

        $orderModel->where('id',$order['id'])->update(['status'=>-1]);

        $this->success('退款成功');

    }
}